import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { getRoutesAPI } from "@/http/api";
import { useRouter } from "@/pinia";
import { ElMessage } from "element-plus";
const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/",
    component: () => import("@/views/home/home.vue"),
    children: [
      { path: "index", component: () => import("@/views/index/index.vue") },
    ],
  },
  {
    path: "/login",
    component: () => import("@/views/login/login.vue"),
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("token");
  const store = useRouter();
  if (store.menus.length === 0 && token) {
    getRoutesAPI().then((res) => {
      if (res.code === 200) {
        store.menus = res.data;
        res.data.splice(res.data.length - 1, 1);
        store.menus.forEach((item: any) => {
          const route: RouteRecordRaw = {
            path: item.path,
            name: item.name,
            component: () => import(`../views/home/home.vue`),
            meta: item.meta,
            children: item.children.map((CItem: any) => ({
              path: item.path + "/" + CItem.path,
              name: CItem.name,
              component: () =>
                import(`../views/${item.name}/${CItem.name}.vue`),
              meta: CItem.meta,
            })),
          };
          // if (item.children[0].name) {
          //   route.redirect = "/" + item.name + "/" + item.children[0].name;
          // }
          router.addRoute(route);
        });
        console.log(router.getRoutes(), "查看现有路由");
        next(to.fullPath);
      }
    });
  } else if (!token && to.path !== "/login") {
    ElMessage.error("请先登录");
    next("/login");
  } else if (token && store.menus.length !== 0 && to.path === "/login") {
    next(from.fullPath);
    ElMessage.warning("请先退出登录再重新登录");
  } else {
    next();
  }
});

export default router;
